using AdminApiTemplate.Api.Controllers.BaseControllers;
using AdminApiTemplate.Api.Enums;
using AdminApiTemplate.Api.Helpers;
using AdminApiTemplate.Cache;
using AdminApiTemplate.Common.Exceptions;
using AdminApiTemplate.Common.Helpers;
using AdminApiTemplate.Services.AdminUser;
using Microsoft.AspNetCore.Mvc;

namespace AdminApiTemplate.Api.Controllers.AdminControllers
{
    /// <summary>
    /// 通用（需要登录）
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CommonController : PermissionRequiredController
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        ///<param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadFileByBase64")]
        public IActionResult UploadFileByBase64([FromBody] UploadFileRequestModel request)
        {
            return new WebHelper(HttpContext, request).Execute(SysUserTypeEnum.AdminUser, AUID.ToString(), () =>
            {
                var host = ConfigHelper.GetSysConfig<string>("ApiHost", null);
                if (string.IsNullOrEmpty(host))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.CodeError, "上传失败，请联系管理员配置ApiHost参数");
                }

                if (string.IsNullOrEmpty(request.FileName))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "文件名称不能为空");
                }

                if (string.IsNullOrEmpty(request.FileData))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "文件内容不能为空");
                }

                if (string.IsNullOrEmpty(request.Module))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "模块不能为空");
                }

                var parts = request.FileData.Split("base64,");
                if (parts.Length!=2)
                {
                    throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "文件内容无效，请填写BASE64字符串");
                }

                var bytes = Convert.FromBase64String(parts[1]);

                var fileExtLimit = new List<string>() { ".xls", ".xlsx" };
                var fileExt = Path.GetExtension(request.FileName);
                if (!fileExtLimit.Contains(fileExt.ToLower()))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, $"仅支持上传{string.Join(",", fileExtLimit)}格式文件");
                }

                var fileName = default(string);
                FileHelper.SaveToFile(bytes, request.Module, request.FileName, ref fileName);

                var fileUrl = $"{host}/api/Home/Download?module={request.Module}&fileName={fileName}";
                return new UploadFileResponseModel
                {
                    FileName=fileName,
                    FileUrl=fileUrl
                };
            });
        }
    }
}
